package com.syqc.monitor.ui.alarm

import android.view.View
import androidx.fragment.app.viewModels
import androidx.recyclerview.widget.LinearLayoutManager
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.kingja.loadsir.core.LoadService
import com.kingja.loadsir.core.LoadSir
import com.syqc.comlib.base.LazyFragment
import com.syqc.comlib.callback.EmptyCallback
import com.syqc.comlib.rx.doAfterChanged
import com.syqc.comlib.utils.startActivityTo
import com.syqc.entity.AlarmCar
import com.syqc.monitor.R
import com.syqc.monitor.databinding.FragmentAlarmTypeCarBinding
import com.syqc.utils.Keys
import com.syqc.utils.ToolsUtil

/**
 *@author joker
 *@time   2023/12/28 15:25
 *@desc
 */
class CarAlarmsFragment :
    LazyFragment<FragmentAlarmTypeCarBinding>(FragmentAlarmTypeCarBinding::inflate) {

    private val mAdapter by lazy { AlarmCarAdapter() }
    private val mVM by viewModels<AlarmCarVM>()
    private var loadService :LoadService<Any>?=null
    override fun initView(view: View) {
        loadService=LoadSir.getDefault().register(binding.recyclerView)
        binding.recyclerView.layoutManager = LinearLayoutManager(requireContext())
        binding.recyclerView.adapter = mAdapter
        binding.editType.setHint(R.string.hint_search_car_plate)
    }

    override fun initData() {
        mVM.alarmsLive.observe(this) {
            mAdapter.setList(it)
            if (it.isNullOrEmpty()) {
                loadService?.showCallback(EmptyCallback::class.java)
                return@observe
            }
            loadService?.showSuccess()
        }
    }

    override fun initEvent() {
        binding.editType.doAfterChanged {
            mVM.search(it)
        }

        mAdapter.setOnItemClickListener { adapter, view, position ->
            if (ToolsUtil.isFastClick()) return@setOnItemClickListener
            val info: AlarmCar = mAdapter.data[position]
            if (info.num == 0) {
                showToast(R.string.toast_no_about_alarm_)
            } else {
                startActivityTo<HandleAlarmInfoActivity>(requireContext()) {
                    putExtra(Keys.INTENT_TITLE, info.carName)
                    putExtra(Keys.INTENT_TEAM_NUM, info.num.toString())
                    putExtra(Keys.INTENT_CAR_ID, info.carId)
                    putExtra(Keys.INTENT_OTHER, true)
                }
            }
        }
    }

    override fun onResume() {
        super.onResume()
        mVM.getCarAlarms()
    }
}

class AlarmCarAdapter : BaseQuickAdapter<AlarmCar, BaseViewHolder>(R.layout.item_alarm_car) {
    override fun convert(holder: BaseViewHolder, item: AlarmCar) {
        item.run { holder.setText(R.id.tvTitle, carPlate).setText(R.id.tvNum, num.toString()) }
    }
}
